<template>
  <div class="plan-submit-container-padding">
    <TopicSelectModal2 ref="topicSelectRef" />
  </div>
  <CommonFooterBar>
    <el-button :loading="loading" @click="handleSubmit">保存为草稿</el-button>
    <el-button type="primary" :loading="loading" @click="handleSubmit(2)">
      确认提交
    </el-button>
  </CommonFooterBar>
</template>

<script setup>
  import TopicSelectModal2 from '@/components/topicSelectModal2'
  import CommonFooterBar from '@/components/commonFooterBar'
  import {
    projectPlanCreate,
    projectPlanGet,
  } from '@/api/project/approval/plan'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { postDraftBoxCreate } from '@/api/project/drafts'

  const route = useRoute()

  const $baseMessage = inject('$baseMessage')
  const { closeTabNavigate } = useCloseTabNavigate()

  const topicSelectRef = ref()

  const loading = ref(false)

  const handleSubmit = (type = 1) => {
    const topicData = topicSelectRef.value.selectTable
    if (!topicData || !topicData.length) {
      return $baseMessage('请选择课题', 'error')
    }
    loading.value = true

    if (type == 2) {
      const params = {
        topicIds: topicData.map((item) => item.id),
      }

      if (route.query?.getType == 1) {
        params.draftBoxId = route.query.id
      }

      projectPlanCreate(params)
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            $baseMessage('上报成功')
            closeTabNavigate()
          }
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      const formData = {
        id: route.query?.getType == 1 ? route.query.id : '',
        type: 'PROJECT_PLAN',
        submitJson: JSON.stringify({
          topicInfos: topicData,
          draftBoxId: route.query?.getType == 1 ? route.query.id : '',
        }),
      }

      postDraftBoxCreate(formData)
        .then((res) => {
          if (res.code == 0 || res.code == 200) {
            $baseMessage('保存草稿成功')
            closeTabNavigate()
          }
        })
        .finally(() => {
          loading.value = false
        })
    }
  }

  const initData = () => {
    projectPlanGet({
      id: route.query.id,
      getType: 1,
    }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        topicSelectRef.value.selectTable = res.data.topicInfos || []
      }
    })
  }

  const newdgg = {
    aaa: null,
  }

  console.log(JSON.parse(JSON.stringify(newdgg)))

  route.query.id && initData()
</script>

<style lang="scss" scoped></style>
